import { defineStore } from "pinia";
import { ref } from "vue";
import {
  createCourse,
  updateCourse,
  getCourseById,
  getCoursesByUserAndWeek,
  deleteCourse,
} from "../api/schedule";

export const useScheduleStore = defineStore("schedule", () => {
  // 定义Event类型
  type Event = {
    id: number;
    userId: number;
    eventType: "course" | "schedule";
    name: string;
    teacher?: string;
    description: string;
    location: string;
    dayOfWeek: number;
    startTime: string;
    endTime: string;
    startWeek: number;
    endWeek: number;
    semester: string;
    color: string;
    status: 0 | 1;
  };

  const events = ref<Event[]>([]);
  const loading = ref(false);
  const error = ref<string | null>(null);

  // 获取一周的课程/日程
  const fetchEvents = async (
    userId: number,
    semester: string,
    week: number
  ) => {
    try {
      loading.value = true;
      const response = await getCoursesByUserAndWeek({
        userId,
        semester,
        week,
      });
      events.value = response.data.map((item: any) => ({
        id: item.id,
        userId: item.userId,
        eventType: item.eventType,
        name: item.name,
        teacher: item.teacher ?? "",
        description: item.description ?? "",
        location: item.location ?? "",
        dayOfWeek: item.dayOfWeek ?? 0,
        startTime: item.startTime ?? "",
        endTime: item.endTime ?? "",
        startWeek: item.startWeek ?? 0,
        endWeek: item.endWeek ?? 0,
        semester: item.semester ?? "",
        color: item.color ?? "",
        status: item.status ?? 0,
      }));
    } catch (err) {
      error.value = "获取课程数据失败";
      console.error(err);
    } finally {
      loading.value = false;
    }
  };

  // 创建课程/日程
  const createEvent = async (eventData: Omit<Event, "id">) => {
    try {
      loading.value = true;
      const response = await createCourse(eventData);
      console.log("创建事件API响应:", response);

      if (response?.data?.data && response.data.data.id) {
        events.value.push(response.data.data);
        return response.data.data;
      }

      if (response?.data?.id) {
        const item = response.data;
        const event: Event = {
          id: item.id,
          userId: item.userId,
          eventType: item.eventType,
          name: item.name,
          teacher: item.teacher ?? "",
          description: item.description ?? "",
          location: item.location ?? "",
          dayOfWeek: item.dayOfWeek ?? 0,
          startTime: item.startTime ?? "",
          endTime: item.endTime ?? "",
          startWeek: item.startWeek ?? 0,
          endWeek: item.endWeek ?? 0,
          semester: item.semester ?? "",
          color: item.color ?? "",
          status: item.status ?? 0,
        };
        events.value.push(event);
        return event;
      }
      throw new Error(response?.data?.message || "无效的API响应格式");
    } catch (err) {
      error.value = `创建课程失败: ${getErrorMessage(err)}`;
      console.error("创建事件失败:", err);
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 更新课程/日程
  const updateEvent = async (eventData: Event) => {
    try {
      loading.value = true;
      const response = await updateCourse(eventData);
      // 只用 response 作为后端返回对象
      const code = Number(response.code);
      const data = response.data;
      // 命中：data为对象且有id
      if (
        data &&
        typeof data === "object" &&
        "id" in data &&
        "userId" in data &&
        "eventType" in data &&
        "name" in data
      ) {
        const updated: Event = {
          id: Number((data as any).id),
          userId: (data as any).userId,
          eventType: (data as any).eventType,
          name: (data as any).name,
          teacher: (data as any).teacher ?? "",
          description: (data as any).description ?? "",
          location: (data as any).location ?? "",
          dayOfWeek: (data as any).dayOfWeek ?? 0,
          startTime: (data as any).startTime ?? "",
          endTime: (data as any).endTime ?? "",
          startWeek: (data as any).startWeek ?? 0,
          endWeek: (data as any).endWeek ?? 0,
          semester: (data as any).semester ?? "",
          color: (data as any).color ?? "",
          status: (data as any).status ?? 0,
        };
        const index = events.value.findIndex((e) => e.id === updated.id);
        if (index !== -1) {
          events.value[index] = { ...events.value[index], ...updated };
        }
        return updated;
      }
      // 命中：code为0/200且data为true/null/空
      if (
        (code === 0 || code === 200) &&
        (typeof data === "boolean" ? data === true : data === null)
      ) {
        return true;
      }
      // 其它情况
      return false;
    } catch (err) {
      error.value = `更新课程失败: ${getErrorMessage(err)}`;
      return false;
    } finally {
      loading.value = false;
    }
  };

  // 删除课程/日程
  const deleteEvent = async (id: number) => {
    try {
      loading.value = true;
      const response = (await deleteCourse({ id })) as unknown as {
        data: { code: number };
      };
      if (response.data && response.data.code === 0) {
        events.value = events.value.filter((e) => e.id !== id);
        return true;
      }
    } catch (err) {
      error.value = "删除课程失败";
      console.error(err);
    } finally {
      loading.value = false;
    }
  };

  return {
    events,
    loading,
    error,
    fetchEvents,
    createEvent,
    updateEvent,
    deleteEvent,
  };
});
function getErrorMessage(err: unknown) {
  if (typeof err === "string") return err;
  if (err instanceof Error) return err.message;
  if (typeof err === "object" && err && "message" in err)
    return (err as any).message;
  return String(err);
}
